package com.alibaba.cloud.clinic.cron;

import com.alibaba.cloud.clinic.constant.ClinicConstant;
import com.alibaba.cloud.clinic.constant.ClinicEnum;
import com.alibaba.cloud.clinic.dao.NativeTransactionMessageMapper;
import com.alibaba.cloud.clinic.dto.ClinicOrderDTO;
import com.alibaba.cloud.clinic.entity.NativeCorrelationData;
import com.alibaba.cloud.clinic.entity.NativeTransactionMessage;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class NativeMessageScheduledTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(NativeMessageScheduledTask.class);

    @Autowired
    private NativeTransactionMessageMapper nativeMessageMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void messageTask() {


        List<NativeTransactionMessage> nativeMessageList = nativeMessageMapper.selectList(
                Wrappers.<NativeTransactionMessage>lambdaQuery()
                        .eq(NativeTransactionMessage::getStatus, ClinicEnum.MESSAGE_STATUS.UNSEND.getValue())
                        .orderByAsc(NativeTransactionMessage::getCreateTime)
        );

        if (CollectionUtils.isEmpty(nativeMessageList)) {
//            LOGGER.info(">>>>>>>>>消息表中没有符合的数据<<<<<<<<<");
            return;
        }

        LOGGER.info(">>>>>>>>>消息队列定时任务开始<<<<<<<<<");

        String messContent = nativeMessageList.get(0).getMessContent();
        ClinicOrderDTO clinicOrderDTO = JSON.parseObject(messContent, ClinicOrderDTO.class);

        NativeCorrelationData correlationData = new NativeCorrelationData();
        correlationData.setId(clinicOrderDTO.getOrderId());
        correlationData.setMessType(ClinicEnum.MESSAGE_TYPE.NATIVE_MESS.getValue());
        correlationData.setExchange(ClinicConstant.TECH_EXCHANGE);
        correlationData.setRoutingKey(ClinicConstant.TECH_ROUTING_KEY);
        correlationData.setMaxRetry(0);
        correlationData.setMessContent(messContent);

        rabbitTemplate.convertAndSend(ClinicConstant.TECH_EXCHANGE, ClinicConstant.TECH_ROUTING_KEY, messContent, correlationData);

        LOGGER.info(">>>>>>>>>消息队列定时任务结束<<<<<<<<<");
    }
}
